""" 

 =(splitobj.py)= v1.2

 splits a file containing navision objects
 in textformat in one file per object
 (C) 2008-present Arno Pucher
  
 Usage: splitobj.py <filename> [-info] <suffix> [YYMMDD] [HHMMSS]
 
   <suffix> is the suffix to append to the filename
   f.i. "ORG" which is expanded to f.i. "CU_1017160-ORG.TXT"
   
   -info ... just list the objects
   
   The object files are stored in directories per object type,
   also are all object ID's filled with 0 to a length of 7.

"""

from sys import *
from os import mkdir
from string import *

# GLOBAL INFO & VARS --------------------------------------

# Structure of an object in the text file:

# OBJECT Codeunit 1017302 Matchcode Functions
# {
# ...
# }

# --- functions -------------------------------------------

def writeObjFile(objType, objID, objName, objFileList, Info):
  
  if Info:
    print objType, objID, objName
    return

  print "writing: ", objType, objID, "File"
  
  if objType == "Table":
    objTypeShort = "TB"
  elif objType == "Form":
    objTypeShort = "FM"
  elif objType == "Report":
    objTypeShort = "RP"
  elif objType == "Dataport":
    objTypeShort = "DP"
  elif objType == "XMLport":
    objTypeShort = "XML"
  elif objType == "Codeunit":
    objTypeShort = "CU"
  elif objType == "MenuSuite":
    objTypeShort = "MS"
  else:
    objTypeShort = "UNKNOWN("+objType+")"
  
  #~ has to be quoted ("/& etc.) => next version, so no obj name is used in filename
  #~ filename = objTypeShort + "_" + objID + "-" + objName + "-" + suffix + ".TXT"
  
  # prepad with 0s
  
  objID = zfill(objID,7)
  
  # create filename
  
  filename = objTypeShort + "_" + objID + "-"  + suffix + ".TXT"
  
  # add sub-directory to filename
  
  #print '1)', filename
  
  if objType == "Table":
    filename = 'Table\\' + filename
  elif objType == "Form":
    filename = 'Form\\' + filename
  elif objType == "Report":
    filename = 'Report\\' + filename
  elif objType == "Dataport":
    filename = 'Dataport\\' + filename
  elif objType == "XMLport":
    filename = 'XMLPort\\' + filename
  elif objType == "Codeunit":
    filename = 'Codeunit\\' + filename
  elif objType == "MenuSuite":
    filename = 'Menusuite\\' + filename
  else:
    objTypeShort = "UNKNOWN("+objType+")"
  
  #print '2)', filename
  
  f = open(filename, 'w')
  f.writelines(objFileList)
  f.close()
  
  #~ for line in objFileList:
    #~ print line,

# --- entry point -----------------------------------------


# argument handling   

if len(argv) == 1:
  print __doc__
  exit(1)
elif len(argv) == 2:
  print "Argument <suffix> needed ..."
  print __doc__
  exit(1)
elif len(argv) == 3:
  filename = argv[1]
  
  if argv[2] == "-info":
    Info = True
  else:
    Info = False
    suffix = argv[2]
    
elif len(argv) == 4:
  filename = argv[1]
  suffix = argv[2]
  datestring = argv[3]
elif len(argv) == 5:
  filename = argv[1]
  suffix = argv[2]
  datestring = argv[3]
  timestring = argv[4]
elif len(argv) > 5:
  print __doc__
  exit(1)

print "\n=(splitobj.py)= v1.2\n"

#~ ArgTest

#~ print "filename:  ", filename
#~ print "suffix:    ", suffix

#~ try:
  #~ print "datestring:", datestring
#~ except: 
  #~ print "only ", len(argv), "arguments"

#~ try:
  #~ print "timestring:", timestring
#~ except: 
  #~ print "only ", len(argv), "arguments"

#~ exit(1);
#
try:  
  file = open(filename, "r")
  lines = file.readlines()
  file.close()
except IOError:
  print 'Could not read file "' + filename + '".'

objectFileList = []
lastLineOfObject = False

if lines > 0:
  try:
    mkdir('Table')
    mkdir('Form')
    mkdir('Report')
    mkdir('Dataport')
    mkdir('XMLPort')
    mkdir('Codeunit')
    mkdir('Menusuite')
  except:
    pass

for line in lines:

  if lastLineOfObject:
    writeObjFile(objectType, objectID, objectName, objectFileList, Info)
    lastLineOfObject = False

  lineTokens = split(line)
  
  if len(lineTokens)!=0:
    
    firstToken = lineTokens[0]
  
    if firstToken == 'OBJECT':
      inBetween = True
      objectFileList = []
      objectFileList.append("")
      objectType = lineTokens[1]
      objectID = lineTokens[2]
      objectName = ''
      name = lineTokens[3:]
      
      for item in name:
        objectName += item + " " 

    try:
      if strip(firstToken[:6]) == "Date":
        line="    Date="+datestring
        print line 
    except:
      pass      
    
    try:
      if strip(firstToken[:6]) == "Date":
        line="    Time="+'[' + timestring + ']'
        print line 
    except:
      pass      


    # Date=11.10.05;
    # Time=17:35:21;


    if line[0] == '}':
      lastLineOfObject = True
      objectFileList.append("")
    
  objectFileList.append(line)    
    
print "\nHave a nice day!"